<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      title="发布选择"
      width="54%"
      :show-close="false"
      :append-to-body="true"
      :close-on-click-modal="false"
      v-dialog-drag
    >
      <div v-loading="isLoading">
        <p class="text-custom-blue mb-4">优惠券基本信息</p>
        <div class="info_box flex flex-wrap">
          <div class="info_item">优惠券编码：{{ couponData.code }}</div>
          <div class="info_item">优惠券类型：{{ handleCouponsType(couponData.type) }}</div>
          <div class="info_item">
            优惠券名称：
            <el-tooltip class="item" effect="dark" :content="couponData.name" placement="top">
              <span class="tool_text">{{ couponData.name }}</span>
            </el-tooltip>
          </div>
          <div class="info_item">
            渠道备注：
            <el-tooltip class="item" effect="dark" :content="couponData.mname" placement="top">
              <span class="tool_text">{{ couponData.mname }}</span>
            </el-tooltip>
          </div>
          <div class="info_item">
            场馆备注：
            <el-tooltip class="item" effect="dark" :content="couponData.bname" placement="top">
              <span class="tool_text">{{ couponData.bname }}</span>
            </el-tooltip>
          </div>
          <div class="info_item">发布渠道：{{ handleSourceType(couponData.sourceType) }}</div>
          <div class="info_item" v-if="couponData.type === 3">
            优惠券面值：{{ couponData.faceValue }}元
          </div>
          <div class="info_item" v-if="couponData.type === 3">
            使用条件：{{ couponData.thresholdAmount }}元
          </div>
          <div class="info_item" v-if="couponData.type === 2">
            抵扣时长：{{ couponData.freeHours }}小时
          </div>
          <div class="info_item" v-if="couponData.type === 1">
            折扣比例：{{ couponData.discount }}折
          </div>
        </div>

        <p class="text-custom-blue mb-4">发布设置</p>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="130px"
          :disabled="isDisabled"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发放总量" prop="total">
                <el-input
                  v-model="form.total"
                  placeholder="请输入发放总量"
                  type="number"
                  :disabled="form.limitType == '3'"
                >
                  <template #append>张</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="每人限领" prop="userTotal">
                <el-input
                  v-model="form.userTotal"
                  placeholder="请输入每人限领"
                  type="number"
                  :disabled="form.limitType == '2'"
                >
                  <template #append>张</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="领取方式" prop="limitType">
                <el-select
                  v-model="form.limitType"
                  placeholder="请选择领取方式"
                  @change="changeLimitType"
                >
                  <el-option
                    v-for="dict in limitTypeOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="有效期类型" prop="lifespanType">
                <el-select
                  v-model="form.lifespanType"
                  placeholder="请选择有效期类型"
                  @change="changeLifespanType"
                >
                  <el-option label="领券当日有效" :value="1" />
                  <el-option label="时间段" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="有效天数" prop="lifespanDay" v-if="form.lifespanType == 1">
                <el-input v-model="form.lifespanDay" placeholder="请输入有效天数" type="number">
                  <template #append>天</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.lifespanType == 2">
              <el-form-item label="有效期" required>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  @change="changeDateRange"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-tabs v-model="activeName">
            <el-tab-pane label="适用范围" name="first">
              <el-form-item label="适用场馆">
                <el-radio-group v-model="form.applyStadiumType" @change="changeApplyStadiumType">
                  <el-radio :label="1">全部场馆</el-radio>
                  <el-radio :label="2">指定场馆</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.applyStadiumType == 2" label="选择场馆" prop="stadiumIds">
                <div class="batch_sel">
                  <el-button
                    icon="Plus"
                    @click="handleStadiumChange"
                    type="primary"
                    size="mini"
                    plain
                    >选择场馆</el-button
                  >
                  <div class="flex flex-wrap mt-3">
                    <el-tag
                      v-for="item in stadiumList"
                      :key="item.id"
                      closable
                      @close="handleCloseStadium(item)"
                      class="mr-2 mb-2"
                      >{{ item.stadiumName }}</el-tag
                    >
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="适用类型">
                <el-radio-group v-model="form.applySportType" @change="changeApplySportType">
                  <el-radio :label="1">全部类型</el-radio>
                  <el-radio :label="2">指定类型</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.applySportType == 2" label="选择类型" prop="sportIds">
                <div class="batch_sel">
                  <el-button icon="Plus" @click="handleSportChange" type="primary" size="mini" plain
                    >选择类型</el-button
                  >
                  <div class="flex flex-wrap mt-3">
                    <el-tag
                      v-for="item in sportList"
                      :key="item.id"
                      closable
                      @close="handleCloseSport(item)"
                      class="mr-2 mb-2"
                      >{{ item.name }}</el-tag
                    >
                  </div>
                </div>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="使用限制" name="second">
              <el-form-item label="时间限制">
                <el-radio-group v-model="form.limitTimeType" @change="changeLimitTimeType">
                  <el-radio :label="1">无限制</el-radio>
                  <el-radio :label="2">指定时间段</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.limitTimeType == 2" label="不可用时间段" prop="limitTime">
                <div class="batch_sel">
                  <el-button icon="Plus" @click="handleTimeChange" type="primary" size="mini" plain
                    >选择时间段</el-button
                  >
                  <div class="flex flex-wrap mt-3">
                    <el-tag
                      v-for="(item, index) in timeList"
                      :key="index"
                      closable
                      @close="handleCloseTime(index)"
                      class="mr-2 mb-2"
                      >{{ item.startTime }}-{{ item.endTime }}</el-tag
                    >
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="用户限制">
                <el-radio-group v-model="form.limitUserType" @change="changeLimitUserType">
                  <el-radio :label="1">无限制</el-radio>
                  <el-radio :label="2">指定用户</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.limitUserType == 2" label="选择用户" prop="limitUserTotal">
                <div class="batch_sel">
                  <el-button icon="Plus" @click="handleUserChange" type="primary" size="mini" plain
                    >选择用户</el-button
                  >
                  <p class="mt-3">
                    已选择<span class="text-custom-blue">{{ form.limitUserTotal }}</span
                    >人
                  </p>
                </div>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="兑换设置" name="third" v-if="form.limitType == '3'">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="兑换码数量" prop="total">
                    <el-input v-model="form.total" placeholder="请输入兑换码数量" type="number">
                      <template #append>个</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="兑换码长度" prop="codeLen">
                    <el-input v-model="form.codeLen" placeholder="请输入兑换码长度" type="number">
                      <template #append>位</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-button
                type="primary"
                @click="handleCreateCode"
                :disabled="!form.total || !form.codeLen"
                >生成兑换码</el-button
              >
              <div class="flex mt-4">
                <div class="redemption_code_left">
                  <div class="left_text" v-for="(item, index) in couponsCodeList" :key="index">
                    {{ item }}
                  </div>
                </div>
                <div class="redemption_code_right">
                  <el-button
                    type="primary"
                    plain
                    class="form_button excel_btn"
                    :disabled="couponsCodeList.length == 0"
                    @click="handleExport"
                    >导出Excel</el-button
                  >
                  <el-button
                    type="primary"
                    plain
                    class="form_button"
                    :disabled="couponsCodeList.length == 0"
                    @click="handleCopy"
                    >复制兑换码</el-button
                  >
                  <p class="form_def_text2">兑换码生成后</p>
                  <p class="form_def_text2">请立即导出保存</p>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="二维码设置" name="fourth" v-if="form.limitType == '4'">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="二维码底图" prop="qrCodeBackgroundImg">
                    <image-upload
                      :limit="1"
                      :fileSize="5"
                      :value="qrCodeBackgroundImgList"
                      @input="changeQrCodeBackgroundImg"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="活动底图" prop="activityBackgroundImg">
                    <image-upload
                      :limit="1"
                      :fileSize="5"
                      :value="activityBackgroundImgList"
                      @input="changeActivityBackgroundImg"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="文字颜色">
                    <div class="color_box">
                      <el-color-picker v-model="form.color" />
                      <span class="ml-2">{{ form.color }}</span>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-button type="primary" @click="handleQrCode">生成二维码</el-button>
              <div class="mt-4 text-center" v-if="form.qrCodeImg">
                <el-image
                  style="width: 200px; height: 200px"
                  :src="form.qrCodeImg"
                  :preview-src-list="[form.qrCodeImg]"
                  fit="contain"
                ></el-image>
                <p class="mt-2">二维码预览</p>
              </div>
            </el-tab-pane>
            <el-tab-pane label="购买设置" name="fifth" v-if="form.limitType == '5'">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="市场价" prop="marketMoney">
                    <el-input v-model="form.marketMoney" placeholder="请输入市场价" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户售价" prop="customerMoney">
                    <el-input
                      v-model="form.customerMoney"
                      placeholder="请输入客户售价"
                      type="number"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="平台服务费" prop="purchaseMoney">
                    <el-input
                      v-model="form.purchaseMoney"
                      placeholder="请输入平台服务费"
                      type="number"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商家实收" prop="totalMoney">
                    <el-input v-model="totalMoney" placeholder="商家实收" type="number" disabled>
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </div>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">提 交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择场馆 -->
    <choose-stadium
      v-if="chooseStadium"
      ref="chooseStadiumRef"
      @refreshShow="handleRefreshShow"
    ></choose-stadium>

    <!-- 选择运动类型 -->
    <choose-motion-type
      v-if="chooseMotionType"
      ref="chooseMotionTypeRef"
      @refreshShow="handleRefreshShow"
    ></choose-motion-type>

    <!-- 选择时间段 -->
    <choose-time
      v-if="chooseTime"
      ref="chooseTimeRef"
      @refreshShow="handleRefreshShow"
    ></choose-time>

    <!-- 选择用户 -->
    <choose-user
      v-if="chooseUser"
      ref="chooseUserRef"
      @refreshShow="handleRefreshShow"
    ></choose-user>

    <!-- 生成兑换码 -->
    <exchange-setting v-if="exchangeSetting" ref="exchangeSettingRef"></exchange-setting>

    <!-- 图片预览 -->
    <image-viewer
      v-if="showViewer"
      :url-list="viewerImgList"
      :file-name="fileName"
      @close="showViewer = false"
    />
    <approval-dialog ref="approvalDialogRef" @sure="goJumpPage"></approval-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { useDict } from '@/utils/dict'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import {
  grantCoupon,
  cancelGrantCoupon,
  getCouponDetail,
  addCouponCode,
  createCouponQrCode,
} from '@/api/coupon/coupon'
import { getStadiumListByIds, getSportListByIds } from '@/api/stadium/stadium'
import { download } from '@/utils/request'
import { debounce } from '@/utils'
import ChooseStadium from './chooseStadium.vue'
import ChooseMotionType from './chooseMotionType.vue'
import ChooseTime from './chooseTime.vue'
import ChooseUser from './chooseUser.vue'
import ExchangeSetting from './exchangeSetting.vue'
import ImageViewer from '@/components/ImageViewer/index.vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import approvalDialog from '@/components/Approval/approvalDialog.vue'

// 字典数据
const { dict } = useDict(['coupon_type', 'platform_type'])

const store = useStore()
const router = useRouter()
const formRef = ref<FormInstance | null>(null)
const approvalDialogRef = ref<InstanceType<typeof approvalDialog> | null>(null)
const chooseStadiumRef = ref<InstanceType<typeof ChooseStadium> | null>(null)
const chooseMotionTypeRef = ref<InstanceType<typeof ChooseMotionType> | null>(null)
const chooseTimeRef = ref<InstanceType<typeof ChooseTime> | null>(null)
const chooseUserRef = ref<InstanceType<typeof ChooseUser> | null>(null)
const exchangeSettingRef = ref<InstanceType<typeof ExchangeSetting> | null>(null)

// 定义响应式数据
const dialogVisible = ref(false)
const isLoading = ref(false)
const submitLoading = ref(false)
const couponId = ref(null)
const isDisabled = ref(false)
const activeName = ref('first')
const dateRange = ref([])
const limitUserTotal = ref(null)
const codeNumber = ref(null)
const codeLength = ref(null)
const batchNum = ref(null)
const showViewer = ref(false)
const fileName = ref('')
const viewerImgList = ref([])

const couponData = ref({
  code: '',
  type: '',
  name: '',
  mname: '',
  bname: '',
  sourceType: '',
  faceValue: '',
  thresholdAmount: '',
  freeHours: '',
  discount: '',
})

const form = reactive({
  couponId: null as number | null,
  total: null as number | null,
  userTotal: null as number | null,
  limitType: '1',
  lifespanType: 1,
  lifespanDay: null as number | null,
  lifespanStartTime: null as string | null,
  lifespanEndTime: null as string | null,
  applyStadiumType: 1,
  stadiumIds: [] as number[],
  applySportType: 1,
  sportIds: [] as number[],
  limitTimeType: 1,
  limitStartTime: null as string | null,
  limitEndTime: null as string | null,
  limitUserType: 1,
  limitUserTotal: null as number | null,
  codeLen: null as number | null,
  qrCodeBackgroundImg: null as string | null,
  activityBackgroundImg: null as string | null,
  color: '#333',
  qrCodeId: null as number | null,
  qrCodeImg: null as string | null,
  marketMoney: null as number | null,
  customerMoney: null as number | null,
  purchaseMoney: null as number | null,
  totalMoney: null as number | null,
  userId: null as number | null,
})

const rules = reactive<FormRules>({
  total: [{ required: true, message: '请输入发放总量', trigger: 'blur' }],
  userTotal: [{ required: true, message: '请输入每人限领', trigger: 'blur' }],
  limitType: [{ required: true, message: '请选择领取方式', trigger: 'change' }],
  lifespanType: [{ required: true, message: '请选择有效期类型', trigger: 'change' }],
  lifespanDay: [{ required: true, message: '请输入有效天数', trigger: 'blur' }],
  stadiumIds: [{ required: true, message: '请选择场馆', trigger: 'change' }],
  sportIds: [{ required: true, message: '请选择类型', trigger: 'change' }],
  limitTime: [{ required: true, message: '请选择不可用时间段', trigger: 'change' }],
  limitUserTotal: [{ required: true, message: '请选择用户', trigger: 'change' }],
  codeLen: [{ required: true, message: '请输入兑换码长度', trigger: 'blur' }],
  qrCodeBackgroundImg: [{ required: true, message: '请上传二维码底图', trigger: 'change' }],
  activityBackgroundImg: [{ required: true, message: '请上传活动底图', trigger: 'change' }],
  marketMoney: [{ required: true, message: '请输入市场价', trigger: 'blur' }],
  customerMoney: [{ required: true, message: '请输入客户售价', trigger: 'blur' }],
  purchaseMoney: [{ required: true, message: '请输入平台服务费', trigger: 'blur' }],
  totalMoney: [{ required: true, message: '请输入商家实收', trigger: 'blur' }],
})

const limitTypeOptions = [
  { value: '1', label: '免费领取' },
  { value: '2', label: '指定发放' },
  { value: '3', label: '兑换领取' },
  { value: '4', label: '二维码领取' },
  { value: '5', label: '购买领取' },
]

const couponsCodeList = ref([])
const stadiumList = ref([])
const sportList = ref([])
const timeList = ref([])

const qrCodeBackgroundImgList = computed(() => {
  return form.qrCodeBackgroundImg
    ? form.qrCodeBackgroundImg
        .split(',')
        .filter(Boolean)
        .map((url) => ({ url }))
    : []
})

const activityBackgroundImgList = computed(() => {
  return form.activityBackgroundImg
    ? form.activityBackgroundImg
        .split(',')
        .filter(Boolean)
        .map((url) => ({ url }))
    : []
})

const totalMoney = computed(() => {
  return (Number(form.customerMoney || 0) - Number(form.purchaseMoney || 0)).toFixed(2)
})

// 监听
watch(
  () => form.limitType,
  (val) => {
    if (val == '3') {
      form.total = null
    } else if (val == '2') {
      form.userTotal = null
    }
  },
)

// 初始化
const init = (id: any) => {
  couponId.value = id
  dialogVisible.value = true
  isLoading.value = true
  getCouponDetail({ couponId: id })
    .then(async (res: any) => {
      couponData.value = res.data
      form.couponId = id
      if (res.data.grantSetting) {
        Object.assign(form, res.data.grantSetting)
        if (form.stadiumIds && form.stadiumIds.length > 0) {
          const stadiumRes = await getStadiumListByIds(form.stadiumIds)
          stadiumList.value = stadiumRes.data
        }
        if (form.sportIds && form.sportIds.length > 0) {
          const sportRes = await getSportListByIds(form.sportIds)
          sportList.value = sportRes.data
        }
        timeList.value = form.limitTimeList || []
        const qrCodeBackRef = this.$refs.qrCodeBackgroundImg
        if (qrCodeBackRef) {
          const qrCodeBackImg = form.qrCodeBackgroundImg?.split(',').filter(Boolean) || []
          qrCodeBackRef.imgList = qrCodeBackRef.fileList = qrCodeBackImg.map((url: string) => ({
            name: '已上传图片',
            url,
          }))
          const activityBackRef = this.$refs.activityBackgroundImg
          const activityBackImg = form.activityBackgroundImg?.split(',').filter(Boolean) || []
          activityBackRef.imgList = activityBackRef.fileList = activityBackImg.map(
            (url: string) => ({
              name: '已上传图片',
              url,
            }),
          )
        }
        form.lifespanType = form.lifespanType || 1
        form.applyStadiumType = form.applyStadiumType || 1
        form.applySportType = form.applySportType || 1
        form.limitTimeType = form.limitTimeType || 1
      }
      isLoading.value = false
    })
    .catch((e: any) => {
      isLoading.value = false
    })
}

// 关闭
const handleClose = async () => {
  await cancelGrantCoupon({ couponId: couponId.value })
  dialogVisible.value = false
}

// 选中数据
const handleRefreshShow = (val: any) => {
  if (!val) return
  // exchangeSetting.value = false
  // chooseStadium.value = false
  // chooseMotionType.value = false
  // chooseUser.value = false
  switch (val.type) {
    case 'chooseStadium':
      form.stadiumIds = val.applyStadium
      stadiumList.value = val.stadiumList
      formRef.value?.clearValidate('stadiumIds')
      break
    case 'chooseMotionType':
      form.sportIds = val.applySport
      sportList.value = val.sportList
      formRef.value?.clearValidate('sportIds')
      break
    case 'chooseTime':
      form.limitStartTime = val.limitStartTime
      form.limitEndTime = val.limitEndTime
      timeList.value = val.timeList
      break
    case 'chooseUser':
      form.limitUserTotal = val.userTotal == 0 ? null : val.userTotal
      form.total = val.userTotal == 0 ? null : val.userTotal
      formRef.value?.clearValidate('limitUserTotal')
      break
    default:
      break
  }
}

// 优惠券类型
const handleCouponsType = (val: any) => {
  const label = dict.value.type.coupon_type.find((item: any) => item.value == val)?.label || '未知'
  return label
}

// 优惠券发布渠道
const handleSourceType = (val: any) => {
  const label =
    dict.value.type.platform_type.find((item: any) => item.value == val)?.label || '未知'
  return label
}

const changeLifespanType = () => {
  formRef.value?.clearValidate('lifespanDay')
}

const changeDateRange = (val: any) => {
  if (val) {
    form.lifespanStartTime = val[0]
    form.lifespanEndTime = val[1]
  } else {
    form.lifespanStartTime = null
    form.lifespanEndTime = null
  }
}

const changeApplyStadiumType = (val: any) => {
  if (val == 1) {
    form.stadiumIds = []
    stadiumList.value = []
    formRef.value?.clearValidate('stadiumIds')
  }
}

const changeApplySportType = (val: any) => {
  if (val == 1) {
    form.sportIds = []
    sportList.value = []
    formRef.value?.clearValidate('sportIds')
  }
}

const changeLimitTimeType = (val: any) => {
  if (val == 1) {
    form.limitStartTime = null
    form.limitEndTime = null
    timeList.value = []
    formRef.value?.clearValidate('limitTime')
  }
}

const changeLimitUserType = (val: any) => {
  if (val == 1) {
    form.limitUserTotal = null
    formRef.value?.clearValidate('limitUserTotal')
  }
}

const changeLimitType = (val: any) => {
  // 清空表单验证
  formRef.value?.clearValidate()
  // 重置表单数据
  form.total = null
  form.userTotal = null
  form.codeLen = null
  couponsCodeList.value = []
  batchNum.value = null
}

// 选择场馆
const handleStadiumChange = () => {
  // chooseStadium.value = true
  const stadiumArr = (form.stadiumIds || []).map((id: number) => ({ id }))
  if (chooseStadiumRef.value) {
    chooseStadiumRef.value.selectData = stadiumArr
    chooseStadiumRef.value.init()
  }
}

// 关闭场馆标签
const handleCloseStadium = (item: any) => {
  const index = form.stadiumIds.indexOf(item.id)
  if (index > -1) {
    form.stadiumIds.splice(index, 1)
    stadiumList.value.splice(index, 1)
  }
  if (form.stadiumIds.length === 0) {
    formRef.value?.clearValidate('stadiumIds')
  }
}

// 选择运动类型
const handleSportChange = () => {
  // chooseMotionType.value = true
  if (chooseMotionTypeRef.value) {
    chooseMotionTypeRef.value.checkList = form.sportIds || []
    chooseMotionTypeRef.value.init()
  }
}

// 关闭运动类型标签
const handleCloseSport = (item: any) => {
  const index = form.sportIds.indexOf(item.id)
  if (index > -1) {
    form.sportIds.splice(index, 1)
    sportList.value.splice(index, 1)
  }
  if (form.sportIds.length === 0) {
    formRef.value?.clearValidate('sportIds')
  }
}

// 选择时间段
const handleTimeChange = () => {
  // chooseTime.value = true
  if (chooseTimeRef.value) {
    chooseTimeRef.value.form.startTime = form.limitStartTime
    chooseTimeRef.value.form.endTime = form.limitEndTime
    chooseTimeRef.value.init()
  }
}

// 关闭时间段标签
const handleCloseTime = (index: number) => {
  timeList.value.splice(index, 1)
  if (timeList.value.length === 0) {
    formRef.value?.clearValidate('limitTime')
  }
}

// 时间限制单选处理
const handleLimitTimeRadioChange = (e: any) => {
  // @ts-ignore
  e == form.limitTimeType ? (form.limitTimeType = '') : (form.limitTimeType = e)
}

// 选择用户
const handleUserChange = () => {
  limitUserTotal.value = form.limitUserTotal
  // chooseUser.value = true
  if (chooseUserRef.value) {
    chooseUserRef.value.init({
      couponId: couponId.value,
      limitUserTotal: form.limitUserTotal,
    })
  }
}

// 生成兑换码
const handleCreateCode = debounce(
  async () => {
    codeNumber.value = form.total
    codeLength.value = form.codeLen
    let hasError = false
    formRef.value?.validateField(['total', 'codeLen'], (valid) => {
      if (valid) {
        hasError = true
        return false
      }
    })
    if (!hasError) {
      const res = await addCouponCode({
        couponId: couponId.value,
        num: form.total,
        len: form.codeLen,
      })
      ElMessage.success(res.msg)
      couponsCodeList.value = res.data.list
      batchNum.value = res.data.batchNum
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 导出兑换码
const handleExport = () => {
  const date = new Date()
  download(
    'cj-stadium/sys/coupon/redemptionCode/export',
    {
      batchNum: batchNum.value,
    },
    `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日_兑换码.xlsx`,
  )
}

// 复制兑换码
const handleCopy = () => {
  const text = couponsCodeList.value.join('\n')
  const textarea = document.createElement('textarea')
  textarea.value = text
  document.body.appendChild(textarea)
  textarea.select()
  document.execCommand('copy')
  document.body.removeChild(textarea)
  ElMessage.success('兑换码已复制到剪贴板')
}

// 生成二维码
const handleQrCode = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      getGenerateQrCode()
    }
  })
}

// 生成二维码
const getGenerateQrCode = async () => {
  const qrCodeForm = {
    couponId: form.couponId,
    qrCodeBackgroundImg: form.qrCodeBackgroundImg,
    activityBackgroundImg: form.activityBackgroundImg,
    color: form.color,
  }
  const res = await createCouponQrCode(qrCodeForm)
  ElMessage.success(res.msg)
  //qrCodeId ex:1409837370986987500
  form.qrCodeId = res.data.id
  //qrCodeImg ex:https://img01.shenshisports.com/img/20250826/508e92f131f547d5a85f66ffd6b3a65f.png
  form.qrCodeImg = res.data.url
  handleLookQrCode()
}

// 查看二维码
const handleLookQrCode = () => {
  showViewer.value = true
  viewerImgList.value = [form.qrCodeImg]
  fileName.value = `${couponData.value.name}_二维码`
}

// 处理二维码底图
const changeQrCodeBackgroundImg = (data: any[]) => {
  form.qrCodeBackgroundImg = data.map((item) => item.url).join(',')
  formRef.value?.clearValidate('qrCodeBackgroundImg')
}

// 处理活动底图
const changeActivityBackgroundImg = (data: any[]) => {
  form.activityBackgroundImg = data.map((item) => item.url).join(',')
  formRef.value?.clearValidate('activityBackgroundImg')
}

// 提交审核
const submitForm = debounce(
  () => {
    try {
      if (!formRef.value) return
      formRef.value.validate(async (valid) => {
        if (valid) {
          if (form.lifespanType == 2) {
            if (!form.lifespanStartTime) {
              ElMessage.error('请选择有效期开始时间')
              return
            }
            if (!form.lifespanEndTime) {
              ElMessage.error('请选择有效期结束时间')
              return
            }
          }
          if (form.limitTimeType == 2) {
            if (!form.limitStartTime || !form.limitEndTime) {
              ElMessage.error('请选择不可用时间段')
              return
            }
          }
          if (form.limitType === '4') {
            if (!form.qrCodeImg) {
              ElMessage.error('请先生成二维码')
              return
            }
            form.activityOtherJson = form.color
          }
          form.userId = store.state.user.id
          form.totalMoney = Number(totalMoney.value)
          form.purchaseMoney = form.purchaseMoney
          form.marketMoney = form.marketMoney
          form.customerMoney = form.customerMoney
          await grantCoupon(form)
          if (approvalDialogRef.value) {
            approvalDialogRef.value.approvalVisible = true
          }
          handleClose()
        }
      })
    } catch (e) {
      ElMessage.error((e as Error) || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 提交审核之后跳转到审核中心
const goJumpPage = () => {
  router.push({ path: '/approval/couPubList' })
}

defineExpose({
  init,
})
</script>

<style scoped lang="scss">
:deep(.el-dialog) {
  border-radius: 6px;
  .el-dialog__header {
    border-radius: 6px 6px 0 0;
    background: rgba(243, 244, 246, 1);
    padding: 12px 15px;
    .el-dialog__title {
      font-size: 14px;
      color: #383838;
    }
  }
  .el-dialog__body {
    padding: 15px 15px 50px;
    max-height: 80vh;
    overflow-y: auto;
  }
  .info_box {
    margin-left: 13px;
    .info_item {
      width: 20%;
      padding-right: 10px;
      box-sizing: border-box;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      margin-bottom: 15px;
      color: #808080;
    }
  }
  .el-form {
    margin: 0 13px;
  }
  .el-form-item {
    margin-bottom: 15px;
    &.radio_item {
      margin-bottom: 0;
    }
    &.change_item {
      margin-bottom: 5px;
    }
  }
  .el-select {
    width: 100%;
  }
  .batch_sel {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    min-height: 141px;
    .el-button {
      margin-left: 14px;
    }
  }
  .el-tabs__nav-wrap {
    padding-left: 23px;
  }
  .div_group {
    margin: 0 0 15px 0;
  }
  .redemption_code_left {
    padding: 12px 2px 12px 15px;
    height: 214px;
    opacity: 1;
    border: 1px solid #a6a6a6;
    overflow-y: auto;
    flex: 1;
    border-radius: 4px;
    margin-top: 16px;
    .left_text {
      font-size: 12px;
      font-weight: 400;
      line-height: 18px;
      color: rgba(56, 56, 56, 1);
      margin: 0 13px 1px 0;
    }
  }

  .redemption_code_right {
    text-align: center;
    margin-top: 16px;
    margin-left: 13px;
    .form_def_text2 {
      font-size: 10px;
      font-weight: 400;
      color: #383838;
      line-height: 12px;
    }
    .form_button {
      display: block;
      width: 113px;
      height: 36px;
      margin: 0 0 21px 0;
      font-size: 14px;
      &.excel_btn {
        margin-bottom: 5px;
      }
    }
  }
  .form_label {
    font-size: 14px;
    color: #0081ff;
    line-height: 21px;
    margin-bottom: 16px;
  }
  .form_tips {
    margin-left: 7px;
    p {
      font-size: 12px;
      line-height: 24px;
      color: #808080;
    }
  }
  .color_box {
    margin-top: 13px;
  }
  .upload_btn {
    width: 119px;
    height: 135px;
    border: 1px solid #e5e5e5;
    background: #f5f7f9;
    border-radius: 4px;
    box-sizing: border-box;
    .upload_add {
      margin-top: 32px;
      img {
        width: 41px;
        height: 41px;
      }
    }
    .upload_txt {
      margin-top: 15px;
      font-size: 12px;
      line-height: 18px;
    }
  }
  .upload-demo .el-upload-list--picture-card .el-upload-list__item {
    width: 119px;
    height: 135px;
  }
  .warn_btn {
    width: 88px;
    background: #ff8d1a;
    color: #fff;
  }
}
</style>
